//
//  AppDelegate.m
//  ios_news
//
//  Created by Han on 14-6-9.
//  Copyright (c) 2014年 ucoder. All rights reserved.
//

#import "AppDelegate.h"
#import "SDWebImageManager.h"


#import "NewsViewController.h"
#import "LiveViewController.h"
#import "MarketViewController.h"
#import "MoreViewController.h"
#import "MobClick.h"
#import "APService.h"
#import "SwipeNavigationController.h"
#import "NewsDetailController.h"



@implementation AppDelegate

@synthesize tabBarCtr;
@synthesize newsCtr;
@synthesize liveCtr;
@synthesize marketCtr;
@synthesize moreCtr;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //
    [self umengTrack];
    
    // Required
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)];
    // Required
    [APService setupWithOption:launchOptions];
    
    
    if (launchOptions) {
        NSDictionary *pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (pushNotificationKey) {
            [APService handleRemoteNotification:pushNotificationKey];
        }
    }
    
    CGRect frame = [[UIScreen mainScreen] bounds];
    NSLog(@"%f -- %f", frame.size.width, frame.size.height);
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    // tabbar未选中颜色
    NSMutableDictionary *tabbarAttrNormal = [NSMutableDictionary dictionary];
    [tabbarAttrNormal setObject:[UIColor darkGrayColor] forKey:NSForegroundColorAttributeName];
    
    // tabbar选中颜色
    NSMutableDictionary *tabbarAttrSelected = [NSMutableDictionary dictionary];
    [tabbarAttrSelected setObject:MAIN_COLOR forKey:NSForegroundColorAttributeName];
    

    
    // 新闻
    self.newsCtr = [[NewsViewController alloc] init];
    SwipeNavigationController *newsNav = [[SwipeNavigationController alloc] initWithRootViewController:self.newsCtr];
    
    UITabBarItem *newsTabBarItem = [[UITabBarItem alloc] init];
    [newsTabBarItem setTitle:@"新闻"];
    [newsTabBarItem setTitleTextAttributes:tabbarAttrNormal forState:UIControlStateNormal];
    [newsTabBarItem setTitleTextAttributes:tabbarAttrSelected forState:UIControlStateSelected];
    [newsTabBarItem setImage:[[UIImage imageNamed:@"tabbar_news_normal.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    [newsTabBarItem setSelectedImage:[[UIImage imageNamed:@"tabbar_news_press.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    //self.newsCtr.tabBarItem = newsTabBarItem;
    newsNav.tabBarItem = newsTabBarItem;
    
    
    // 直播
    self.liveCtr = [[LiveViewController alloc] init];
    SwipeNavigationController *liveNav = [[SwipeNavigationController alloc] initWithRootViewController:self.liveCtr];
    
    UITabBarItem *liveTabBarItem = [[UITabBarItem alloc] init];
    [liveTabBarItem setTitle:@"直播"];
    [liveTabBarItem setTitleTextAttributes:tabbarAttrNormal forState:UIControlStateNormal];
    [liveTabBarItem setTitleTextAttributes:tabbarAttrSelected forState:UIControlStateSelected];
    [liveTabBarItem setImage:[[UIImage imageNamed:@"tabbar_live_normal.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ]];
    [liveTabBarItem setSelectedImage:[[UIImage imageNamed:@"tabbar_live_press.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    //self.liveCtr.tabBarItem = liveTabBarItem;
    liveNav.tabBarItem = liveTabBarItem;
    
    
    // 行情
    self.marketCtr = [[MarketViewController alloc] init];
    SwipeNavigationController *marketNav = [[SwipeNavigationController alloc] initWithRootViewController:self.marketCtr];
    
    UITabBarItem *marketTabBarItem = [[UITabBarItem alloc] init];
    [marketTabBarItem setTitle:@"行情"];
    [marketTabBarItem setTitleTextAttributes:tabbarAttrNormal forState:UIControlStateNormal];
    [marketTabBarItem setTitleTextAttributes:tabbarAttrSelected forState:UIControlStateSelected];
    [marketTabBarItem setImage:[[UIImage imageNamed:@"tabbar_market_normal.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ]];
    [marketTabBarItem setSelectedImage:[[UIImage imageNamed:@"tabbar_market_press.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    //self.marketCtr.tabBarItem = marketTabBarItem;
    marketNav.tabBarItem = marketTabBarItem;
    
    
    // 更多
    self.moreCtr = [[MoreViewController alloc] init];
    SwipeNavigationController *moreNav = [[SwipeNavigationController alloc] initWithRootViewController:self.moreCtr];
    
    UITabBarItem *moreTabBarItem = [[UITabBarItem alloc] init];
    [moreTabBarItem setTitle:@"更多"];
    [moreTabBarItem setTitleTextAttributes:tabbarAttrNormal forState:UIControlStateNormal];
    [moreTabBarItem setTitleTextAttributes:tabbarAttrSelected forState:UIControlStateSelected];
    [moreTabBarItem setImage:[[UIImage imageNamed:@"tabbar_more_normal.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ]];
    [moreTabBarItem setSelectedImage:[[UIImage imageNamed:@"tabbar_more_press.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    self.moreCtr.tabBarItem = moreTabBarItem;
    moreNav.tabBarItem = moreTabBarItem;
    
    
    // tabbar导航
    self.tabBarCtr = [[UITabBarController alloc] init];
    self.tabBarCtr.delegate = self;
    self.tabBarCtr.tabBar.translucent = NO;  // tabar不透明
    //self.tabBarCtr.tabBar.barTintColor = [UIColor redColor]; // tabbar背景颜色
    
    tabBarCtr.viewControllers = [NSArray arrayWithObjects:newsNav, liveNav, marketNav, moreNav, nil];
    
    self.window.rootViewController = tabBarCtr;
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    SDWebImageManager *mgr = [SDWebImageManager sharedManager];
    [mgr cancelAll];
    [mgr.imageCache clearMemory];
}


// 禁止横屏
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}


- (void)umengTrack {
    //    [MobClick setCrashReportEnabled:NO]; // 如果不需要捕捉异常，注释掉此行
    //[MobClick setLogEnabled:YES];  // 打开友盟sdk调试，注意Release发布时需要注释掉此行,减少io消耗
    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    //
    [MobClick startWithAppkey:@"53cde3c956240bbd951a3428" reportPolicy:BATCH   channelId:@"ucoder"];
    //   reportPolicy为枚举类型,可以为 REALTIME, BATCH,SENDDAILY,SENDWIFIONLY几种
    //   channelId 为NSString * 类型，channelId 为nil或@""时,默认会被被当作@"App Store"渠道
    
    //      [MobClick checkUpdate];   //自动更新检查, 如果需要自定义更新请使用下面的方法,需要接收一个(NSDictionary *)appInfo的参数
    //    [MobClick checkUpdateWithDelegate:self selector:@selector(updateMethod:)];
    
    [MobClick updateOnlineConfig];  //在线参数配置
    
    //    1.6.8之前的初始化方法
    //    [MobClick setDelegate:self reportPolicy:REALTIME];  //建议使用新方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onlineConfigCallBack:) name:UMOnlineConfigDidFinishedNotification object:nil];
    
}

- (void)onlineConfigCallBack:(NSNotification *)note {
    
    //NSLog(@"online config has fininshed and note = %@", note.userInfo);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    
    
    // Required
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{

    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNoData);
    
    NSLog(@"%@", userInfo);
    
    self.pushInfo = userInfo;
    
    if (application.applicationState == UIApplicationStateActive)
    {
        NSDictionary *aps = [userInfo valueForKey:@"aps"];
        NSString *alertInfo = [aps valueForKey:@"alert"];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"要闻推送" message:alertInfo delegate:self cancelButtonTitle:@"忽略" otherButtonTitles:@"点击查看", nil];
        alert.tag = 8888;
        [alert show];
    } else if (application.applicationState == UIApplicationStateInactive)
    {
        [self pushNewsDetailViewWithInfo:userInfo];
        NSLog(@"我在前端未激活丫 我在前端未激活丫");
    } else {
        [self pushNewsDetailViewWithInfo:userInfo];
        NSLog(@"我在后台丫 我在后台丫");
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 8888)
    {
        if (buttonIndex == 1)
        {
            [self pushNewsDetailViewWithInfo:self.pushInfo];
        }
    }
}


#pragma mark - 处理推送的消息
- (void)pushNewsDetailViewWithInfo:(NSDictionary *)info
{
    [UIApplication sharedApplication].applicationIconBadgeNumber--;
    
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    [tabBarController setSelectedIndex:0];
    //if ([info valueForKey:@"nid"]) {
        //NewsEntity *news = [[NewsEntity alloc]init];
        //news.nid = [info valueForKey:@"nid"];
        UINavigationController *newsvc = (UINavigationController *)tabBarController.selectedViewController;
        //NewsDetailController *detail = [[NewsDetailController alloc]init];
        NewsDetailController *detail = [[NewsDetailController alloc] initWithNibName:nil bundle:nil nid: 208535];
        
        //NSMutableArray *array = [[NSMutableArray alloc]init];
        //[array addObject:news];
        //detail.sourceArr = array;
        //detail.defaultIndex = 0;
        detail.hidesBottomBarWhenPushed = YES;
        [newsvc pushViewController:detail animated:YES];
    //}
}

@end
